package com.qyer.lxp.common.framework.extension;

import com.alibaba.dubbo.rpc.protocol.rest.support.LoggingFilter;

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.ext.WriterInterceptor;
import javax.ws.rs.ext.WriterInterceptorContext;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by jiangping on 16/6/3.
 */
public class ResponseTraceInterceptor implements WriterInterceptor {
    /**
     * Interceptor method wrapping calls to {@link MessageBodyWriter#writeTo} method.
     * The parameters of the wrapped method called are available from {@code context}.
     * Implementations of this method SHOULD explicitly call
     * {@link WriterInterceptorContext#proceed} to invoke the next interceptor in the chain,
     * and ultimately the wrapped {@code MessageBodyWriter.writeTo} method.
     *
     * @param context invocation context.
     * @throws IOException             if an IO error arises or is thrown by the wrapped
     *                                 {@code MessageBodyWriter.writeTo} method.
     * @throws WebApplicationException thrown by the wrapped {@code MessageBodyWriter.writeTo} method.
     */
    @Override
    public void aroundWriteTo(WriterInterceptorContext context) throws IOException, WebApplicationException {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        OutputStream output = context.getOutputStream();
        buffer.writeTo(output);
        context.setOutputStream(output);
        System.out.println("The contents of response body is: \n" + new String(buffer.toByteArray(),"UTF-8") + "\n");
        context.proceed();
    }
}
